package club.janna.jrpc.util;

import club.janna.jrpc.rpc.Invoker;
import club.janna.jrpc.rpc.RPCInvocation;
import club.janna.jrpc.rpc.RPCResponse;

import java.lang.reflect.Proxy;

/**
 * @author Panbo.Guo
 */
public class ProxyFactory {

    /**
     * 获取代理对象
     * @param invoker
     * @param tClass
     * @return
     */
    public static <T> T getProxyObject(Invoker invoker, Class<T> tClass) {
        return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, (proxy, method, args) -> {
            // 如果是Object的方法，调用代理对象的
            if(method.getDeclaringClass() == Object.class) {
                return method.invoke(proxy, args);
            }

            RPCInvocation rpcInvocation = new RPCInvocation();
            rpcInvocation.setId(IDGenerator.get());
            rpcInvocation.setTarget(tClass);
            rpcInvocation.setMethod(method.getName());
            rpcInvocation.setParameterTypes(method.getParameterTypes());
            rpcInvocation.setArgs(args);
            RPCResponse<?> response = invoker.invoker(rpcInvocation);
            if(response.getStatus() != RPCResponse.Status.SUCCESS) {
                throw new RuntimeException("执行远程方法出错", response.getThrowable());
            }
            return response.getResult();
        });
    }
}
